import api from '../../api/index';
import { sdk } from '../../config/sdk';
Page({
  data: {
    modalName: 'viewModal',
    campuss: [],
    weekday: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"],
    xIndex: new Date().getDay() == 0 ? new Date().getDay() + 1 : new Date().getDay(),
    pIndex: 1,
    wIndex: 0
  },

  onLoad(options) {
    this.getCampus();
    let weeks = [];
    let period = [];
    for (let i = 1; i <= 20; i++) {
      weeks.push(`第${i}周`);
    }
    for (let i = 1; i <= 11; i++) {
      period.push(`第${i}节`);
    }
    this.setData({ weeks, period });
  },

  showModal(e) {
    this.setData({ modalName: e.currentTarget.dataset.target });
  },

  hideModal(e) {
    this.setData({ modalName: null });
  },

  // 选择校区
  campussChange(e) {
    this.setData({ cIndex: e.detail.value, bIndex: null });
    this.getBuilDing();
  },

  // 选择教学楼
  built() {
    const { cIndex } = this.data;
    if (!cIndex) return this.$error('请先选择校区');
  },

  builtChange(e) {
    this.setData({ bIndex: e.detail.value });
  },

  // 选择周次
  week() {
    const { bIndex } = this.data;
    if (!bIndex) {
      this.$error('请先选择教学楼');
    }
  },
  weekChange(e) {
    this.setData({ wIndex: e.detail.value })
  },

  // 选择星期
  weekdayChange(e) {
    this.setData({ xIndex: parseInt(e.detail.value) + 1 });
  },

  // 选择节次
  periodChange(e) {
    this.setData({ pIndex: parseInt(e.detail.value) + 1 });
  },

  // 获取校区
  async getCampus() {
    wx.showLoading({ title: '校区查询中...', mask: true });
    const { code, message, data } = await sdk.request({ url: api.getCampus });
    wx.hideLoading();
    if (code != 1000) return this.$error(message);
    this.setData({
      campuss: data
    })
  },

  // 获取教学楼
  async getBuilDing() {
    const { year, term } = sdk.isDate.getDate();
    const { campuss, cIndex } = this.data;
    const { code, message, data } = await sdk.request({ url: api.getBuilDing, data: { campus: campuss[cIndex].id, year, term } });
    if (code != 1000) return this.$error(message);
    this.setData({
      builtList: data
    });
  },

  // 查询空闲教室
  async getClassRoom() {
    const self = this;
    const { campuss, cIndex, builtList, bIndex, wIndex, xIndex, pIndex } = this.data;
    if (!cIndex && !bIndex) return this.$error('参数错误');
    const { year, term } = sdk.isDate.getDate();
    const params = {
      year,
      term,
      campus: campuss[cIndex].id,
      building: builtList[bIndex].JXLDM,
      week: parseInt(wIndex) + 1,
      day: xIndex,
      period: pIndex
    }
    const { code, message, data } = await sdk.request({ url: api.getRoom, data: params });
    if (code != 1000) return this.$error(message);
    self.setData({
      classRoom: data,
      modalName: null,
      animation: true
    });
    const timer = consetTimeout(function () {
      self.setData({
        animation: false
      });
      clearTimeout(timer);
    }, 3000);
  },
})